<template>
    <div class="add-product-container">
        <div class="page-header">
            <h1>{{ status == 1 ? '新增' : '修改' }}商品</h1>
        </div>

        <form class="product-form" @submit.prevent="handleSubmit">
            <!-- 商品图片上传 -->
            <div class="form-group">
                <label class="form-label">商品图片</label>
                <div class="image-upload">
                    <van-uploader v-if="(status == 1 || status == 2) && !product.img" :after-read="afterRead" max-count="1"
                        :before-delete="beforeDelete" v-model="fileList" accept="image/*" />
                    <div v-else class="upload">
                        <img class="img-upload" @click="preView" :src="$Img + product.img" alt="">
                        <van-icon @click="imgDelect" class="upload-icon" name="cross" size="20" />
                    </div>


                </div>
            </div>

            <!-- 商品名称 -->
            <div class="form-group">
                <label class="form-label" for="productName">商品名称</label>
                <input type="text" id="productName" v-model="product.name" class="form-control" placeholder="请输入商品名称"
                    required>
            </div>

            <!-- 商品价格 -->
            <div class="form-group">
                <label class="form-label" for="productPrice">商品价格（¥）</label>
                <div class="price-input">
                    <input type="number" id="productPrice" v-model="product.price" class="form-control" placeholder="0.00"
                        step="0.01" min="0" required>
                </div>
            </div>

            <!-- 商品颜色 -->
            <!--   <div class="form-group">
                <label class="form-label" for="productColor">商品颜色</label>
                <input type="text" id="productColor" v-model="product.color" class="form-control" placeholder="请输入商品颜色"
                    required>
            </div> -->

            <!-- 商品数量 -->
            <!--  <div class="form-group">
                <label class="form-label">商品数量</label>
                <div class="quantity-control">
                    <button type="button" class="quantity-btn minus" @click="changeQuantity(-1)"
                        :disabled="product.quantity <= 1">
                        -
                    </button>
                    <input type="number" v-model="product.quantity" class="quantity-input" min="1" required>
                    <button type="button" class="quantity-btn plus" @click="changeQuantity(1)">
                        +
                    </button>
                </div>
            </div> -->

            <!-- 详情介绍 -->
            <div class="form-group">
                <label class="form-label" for="producttext">详情介绍</label>
                <textarea id="producttext" v-model="product.text" class="form-control" placeholder="请输入商品简介（不超过20字）"
                    maxlength="20" rows="2" required></textarea>
                <p class="char-count">{{ product.text.length }}/20</p>
            </div>

            <!-- 是否促销 -->
            <div class="form-group">
                <label class="form-label">是否促销</label>
                <div class="radio-group">
                    <label class="radio-item">
                        <input type="radio" name="isPromotion" value="true" v-model="product.isPromotion">
                        <span>是</span>
                    </label>
                    <label class="radio-item">
                        <input type="radio" name="isPromotion" value="false" v-model="product.isPromotion">
                        <span>否</span>
                    </label>
                </div>
            </div>
            <!-- 赠送代金券 -->
          <!--   <div class="form-group" v-if="product.isPromotion === 'true'">
                <label class="form-label" for="voucher">赠送代金券金额(¥)</label>
                <div class="price-input">
                    <input type="number" id="voucher" v-model="product.voucher" class="form-control" placeholder="0.00"
                        step="0.01" min="0">
                </div>
                <p class="form-hint">不填写则默认不赠送</p>
            </div> -->

            <!-- 提交按钮 -->
            <button type="submit" class="btn submit-btn">提交</button>
        </form>
        <van-image-preview v-model:show="show" :images="[$Img + product.img]">
        </van-image-preview>
    </div>
</template>
  
<script>
import axios from "axios";
import throttle from "@/utils/debounce.js";
import { getuser, storeFront, editStore } from "@/api/fulfil.js";
export default {
    name: 'storeIndex',
    data() {
        return {
            product: {
                name: '',
                price: '',
                color: '',
                text: '',
                num: '1',
                isPromotion: 'false',
                voucher: '',
                img: ''
            },
            show:false,
            fileList: [],//图片数组
            status: 1,//1新增 2修改
        };
    },
    activated() {
        console.log(this.$route.query);
        this.status = this.$route.query.status;
        //修改
        if (this.$route.query.status == 2) {
            let query = JSON.parse(this.$route.query.product)

            this.product = query;
            console.log(query, 'query');
            this.product.isPromotion = query.isPromotion == '1' ? 'true' : 'false'
        }
    },
    methods: {
        //预览图片
        preView() {
            this.show = true;
        },
        //删除图片
        imgDelect() {
            this.product.img = '';
        },
        afterRead(file) {
            console.log(file, 'file');
            var formData = new FormData();
            formData.append("file", file.file);
            // 此时可以自行将文件上传至服务器
            getuser(formData)
                .then((res) => {
                    console.log(res, 'res');
                    if (res.data.code == 0) {
                        this.product.img = res.data.data;
                        this.$toast("上传成功");
                    } else {
                        this.$toast(res.data.msg);
                    }

                })
                .catch((error) => {
                    console.log(error);
                });
        },
        //修改商品
        editStore: throttle(function () {
            {
                let query = this.product;
                console.log(this.product, 'this.product');
                query.isPromotion = this.product.isPromotion == 'true' ? '1' : '0';
                query.agentid = localStorage.getItem("agentid");
                query.num = '1';
                editStore(query)
                    .then((res) => {
                        if (res.data.code == 0) {

                            this.$toast("修改成功");
                            this.$router.go(-1);
                        } else {
                            this.$toast(res.data.msg);
                        }

                    })
                    .catch((error) => {
                        console.log(error);
                    });
            }
        }, 1500),
        //新增商品
        storeFront: throttle(function () {
            {
                let query = this.product;
                console.log(this.product, 'this.product');
                query.isPromotion = this.product.isPromotion == 'true' ? '1' : '0';
                query.agentid = localStorage.getItem("agentid");
                query.num = this.product.num;
                query.price = this.product.price.toString();
                storeFront(query)
                    .then((res) => {
                        if (res.data.code == 0) {

                            this.$toast("新增成功");
                            this.$router.go(-1);
                        } else {
                            this.$toast(res.data.msg);
                        }

                    })
                    .catch((error) => {
                        console.log(error);
                    });
            }
        }, 1500),
        // 删除文件
        beforeDelete(file, detail) {
            this.fileList.map((item, i) => {
                if (item.file.name == file.file.name) {
                    this.fileList.splice(i, 1);
                }
            });
            this.product.img = '';
            this.$toast("删除成功");
        },

        // 改变数量
        changeQuantity(step) {
            this.product.quantity = Math.max(1, this.product.quantity + step);
        },

        // 提交表单
        handleSubmit() {
            // 表单验证
            if (!this.product.img) {
                alert('请上传商品图片');
                return;
            }

            if (!this.product.name.trim()) {
                alert('请输入商品名称');
                return;
            }

            if (!this.product.price || this.product.price <= 0) {
                alert('请输入有效的商品价格');
                return;
            }
            if (this.status == 1) {
                this.storeFront();
            } else {
                this.editStore();
            }


            // 这里可以添加发送数据到服务器的逻辑
            this.resetForm();
        },

        // 取消操作
        handleCancel() {
            if (confirm('确定要取消吗？已填写的内容将被清空')) {
                this.resetForm();
            }
        },

        // 重置表单
        resetForm() {
            this.product = {
                name: '',
                price: '',
                color: '',
                num: '1',
                text: '',
                isPromotion: 'false',
                voucher: '',
                img: '',
            };
        }
    }
};
</script>
  
<style scoped>
.add-product-container {
    width: 100%;
    margin: 0 auto;
    padding: .5rem;
    background-color: #f9f9f9;
    min-height: 100vh;
    box-sizing: border-box;
}

.page-header {
    text-align: center;
    border-bottom: 1px solid #eee;
}

.page-header h1 {
    font-size: .5rem;
    color: #333;
    margin: 0 auto;
    text-align: center;
}

.product-form {
    background-color: #fff;
    padding: .3125rem;
    border-radius: .1rem;
    box-shadow: 0 .025rem .125rem rgba(0, 0, 0, 0.05);
}

.form-group {
    margin-bottom: .25rem;
}

.form-label {
    display: block;
    margin-bottom: .1rem;
    font-weight: 500;
    color: #333;
    font-size: .375rem;
}

.form-control {
    width: 100%;
    padding: .3rem .375rem;
    border: 1px solid #ddd;
    border-radius: .05rem;
    font-size: .35rem;
    box-sizing: border-box;
    transition: border-color 0.2s;
}

.form-control:focus {
    outline: none;
    border-color: #42b983;
}

/* 图片上传区域 */
.image-upload {
    margin-top: .0625rem;
}

.upload-area {
    width: 25%;
    height: 2.25rem;
    border: 2px dashed #ddd;
    border-radius: .05rem;
    position: relative;
    overflow: hidden;
    cursor: pointer;
    transition: border-color 0.2s;
}

.upload-area:hover {
    border-color: #42b983;
}

.upload-area.hasImage {
    border-style: solid;
}

.file-input {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
    z-index: 10;
}

.upload-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #999;
}

.icon-upload {
    font-size: .375rem;
    margin-bottom: .125rem;
}

.preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.remove-image {
    position: absolute;
    top: .125rem;
    right: .125rem;
    width: .375rem;
    height: .375rem;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    border: none;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 20;
}

.icon-remove {
    font-size: .2rem;
}

/* 数量控制 */
.quantity-control {
    display: flex;
    align-items: center;
    width: 4rem;
}

.quantity-btn {
    width: 1rem;
    height: 1rem;
    border: 1px solid #ddd;
    background-color: #f5f5f5;
    font-size: .5rem;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.2s;
}

.quantity-btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.quantity-btn.minus {
    border-right: none;
    border-radius: .05rem 0 0 4px;
}

.quantity-btn.plus {
    border-left: none;
    border-radius: 0 .05rem .05rem 0;
}

.quantity-input {
    width: 2.5rem;
    height: .9rem;
    border: .025rem solid #ddd;
    text-align: center;
    font-size: .5rem;
}

/* 价格输入 */
.price-input {
    display: flex;
    align-items: center;
}

.currency-symbol {
    padding: 0 .125rem;
    color: #666;
    font-size: .2rem;
}

/* 单选按钮组 */
.radio-group {
    display: flex;
    gap: .25rem;
}

.radio-item {
    display: flex;
    align-items: center;
    cursor: pointer;
}

.radio-item input {
    margin-right: .0625rem;
}

/* 字符计数 */
.char-count {
    text-align: right;
    margin: .0625rem 0 0;
    font-size: .35rem;
    color: #999;
}

/* 表单提示 */
.form-hint {
    margin: .0625rem 0 0;
    font-size: .35rem;
    color: #999;
}

/* 按钮样式 */
.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: .1875rem;
    margin-top: .375rem;
}

.btn {
    padding: .125rem .25rem;
    border-radius: .05rem;
    font-size: .175rem;
    cursor: pointer;
    transition: all 0.2s;
    border: none;
}

.cancel-btn {
    background-color: #f5f5f5;
    color: #666;
}

.cancel-btn:hover {
    background-color: #e9e9e9;
}

.submit-btn {
    width: 90%;
    height: 1rem;
    position: absolute;
    bottom: .1rem;
    left: 5%;
    background-color: #42b983;
    color: white;
    border-radius: .5rem;
    text-align: center;
    font-size: .5rem;
}

.submit-btn:hover {
    background-color: #359e75;
}

.img-upload {
    width: 1.425rem;
    height: 1.425rem;
}

.upload {
    width: 1.425rem;
    height: 1.425rem;
    position: relative;
}

.upload-icon {
    position: absolute;
    top: 0;
    right: 0;
}</style>
  